package Test.FOURTH.four;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileUploadServer {
    private final static int SERVER_PORT=8001;
    private final static int BACKLOG=50;
    private ServerSocket serverSocket;
    private Socket socket;
    private InputStream is;

    public FileUploadServer(){
        try {
            serverSocket=new ServerSocket(SERVER_PORT,BACKLOG);
            System.out.println("--文件上传服务器启动成功--");
            System.out.println("--等待文件上传中--");
            socket=serverSocket.accept();

            is=socket.getInputStream();
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception{
        FileUploadServer fileUploadServer=new FileUploadServer();

        File file=new File("ServerUploadSave.txt");

        /**
         * 初始化存储Client上传的文件的txt文档
         * 存在则删除并建立新文件
         * 否则直接建立新文件
         */
        if (file.exists()){
            file.delete();
            file.createNewFile();
            System.out.println("文件初始化成功");
        }else{
            file.createNewFile();
        }

        FileOutputStream fos=new FileOutputStream(file);

        BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fos);

        BufferedInputStream bufferedInputStream=new BufferedInputStream(fileUploadServer.is);

        int c=0;
        char ch;
        while (c!=-1){
            c=bufferedInputStream.read();
            ch=(char)c;
            System.out.print(ch);
            bufferedOutputStream.write(c);
        }
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
        bufferedInputStream.close();
    }

}
